package com.example.task;

import com.example.entity.Orders;
//import com.example.mapper.OrderMapper;
import com.example.entity.ShoppingCart;
import com.example.mapper.InventoryDao;
import com.example.mapper.OrdersDao;
import com.example.utils.RedisUtil;
import com.example.vo.InventoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 1. @ClassDescription: 处理订单定时任务
 * 2. @author: Z
 * 3. @date: 2023年12月16日 13:35
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private InventoryDao inventoryDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * @description: 处理订单超时方法
     * @time: 2023/12/16 13:38
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟触发一次
    public void processTimeoutOrder(){
        log.info("处理订单超时任务，:{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = ordersDao.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);

        if(ordersList!=null && ordersList.size()>0){
            List<ShoppingCart> shoppingCartList = new ArrayList<>();
            List<String> keys = new ArrayList<>();
            for(Orders orders : ordersList){
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                ordersDao.update(orders);
                //更新库存
                String key = "order_" + orders.getNumber();
                keys.add(key);
                List<ShoppingCart> list = (List<ShoppingCart>) redisTemplate.opsForValue().get(key);
                if(list!=null)
                    shoppingCartList.add(list.get(0));
            }
            inventoryDao.updateBatch2(shoppingCartList);
            if(keys != null)
                for(String key:keys){
                    redisTemplate.delete(key);
                }
            //清空缓存
            redisUtil.cleanRedis();
        }


    }
//
//    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点触发
//    public void processDeliveryOrder(){
//        log.info("定时处理处于派生中的订单：{}",LocalDateTime.now());
//
//        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
//
//        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
//
//        if(ordersList!=null && ordersList.size()>0){
//            for(Orders orders : ordersList){
//                orders.setStatus(Orders.COMPLETED);
//                orderMapper.update(orders);
//            }
//        }
//    }
}
